import json
from PIL import Image
import random
import random_name
import filenamee

# 随机截图的


# 循环次数
num = 1
# 文件地址
# pic_folder = 'D:/pic'
pic_folder='C:/Users/EDY/Desktop/05'
# 调用函数,如果json和图片文件相同则存入数组
same_name_files = random_name.get_same_name_files(pic_folder)
for i in same_name_files:
    print(i[0])
    # 读取图片
    img = Image.open(pic_folder + "/" + i[0])
    # 读取JSON文件
    with open(pic_folder + '/' + i[1], 'r', encoding='utf-8') as f:
        data = json.load(f)
    # 提取坐标
    coordinates = []
    # 后list（data
    # 这里for data 然
    # 3we
    for shape in data['shapes']:
        # 硬代码，之后修改，先用着
        if shape['label'] == '1':
            for point in shape['points']:
                coordinates.append((point[0], point[1]))

    for j in range(int(len(coordinates) / 2)):
        le = round(coordinates[j * 2][0])
        u = round(coordinates[j * 2][1])
        r = round(coordinates[j * 2 + 1][0])
        lo = round(coordinates[j * 2 + 1][1])
        for k in range(num):
            xx = random.randint(-1, 1)
            yy = random.randint(-1, 1)
            # 生成随机左上角和右下角坐标
            left = le + xx
            upper = u + yy
            right = r + xx
            lower = lo + yy

            if left > right:
                left, right = right, left
            if upper > lower:
                upper, lower = lower, upper
            # 剪裁图像
            cropped = img.crop((left, upper, right, lower))
            # 查看图片
            # Image._show(cropped)
            # 随机生产6位随机数加大小写字母
            f_name = filenamee.generate_random_filename(6)
            # 生成随机文件名
            # filename = "pil_cut_" + f_name + ".png"
            filename = "pil_cut_" +i[0] +f_name + ".png"
            # 保存剪裁后的图像
            cropped.save("D:/new/" + filename)
